package com.wx.asset.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wx.asset.dao.AssetDao;
import com.wx.asset.ecommerce.AssetSubTypeEnum;
import com.wx.asset.ecommerce.AssetTypeEnum;
import com.wx.asset.entity.Asset;
import com.wx.asset.model.AssetTypeSumResponse;
import com.wx.asset.service.AssetService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
  * (asset)表服务实现类
  * @author liuwenxuan
  * @TableName asset
  * @createDate 20250409.01
  */
@Service("assetService")
public class AssetServiceImpl extends ServiceImpl<AssetDao, Asset> implements AssetService {

    @Resource
    private AssetDao assetDao;

    @Override
    public Object getAssetSum(Long userId) {
        List<Asset> assets = assetDao.selectList(new LambdaQueryWrapper<Asset>().eq(Asset::getUserId, userId));
        BigDecimal sum  = new BigDecimal(0);
        BigDecimal dispatchSum = new BigDecimal(0);
        for (Asset asset : assets) {
            sum = sum.add(BigDecimal.valueOf(asset.getAmount()));
            String type = asset.getType();
            if (AssetTypeEnum.BANK.getName().equals(type)||AssetTypeEnum.MONEY.getName().equals(type)){
                dispatchSum = dispatchSum.add(BigDecimal.valueOf(asset.getAmount()));
            }else if(AssetTypeEnum.ZFB.getName().equals(type)||AssetTypeEnum.WX.getName().equals(type)){
                String subType = asset.getSubType();
                if (AssetSubTypeEnum.BALANCE.getName().equals(subType)||subType.equals(AssetSubTypeEnum.BALANCE_BAO.getName())){
                    dispatchSum = dispatchSum.add(BigDecimal.valueOf(asset.getAmount()));
                }
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("sum", sum);
        map.put("dispatchSum", dispatchSum);
        return map;
    }

    @Override
    public Object getAssetTypeSum(Long userId) {
        List<Asset> assets = assetDao.selectList(new LambdaQueryWrapper<Asset>().eq(Asset::getUserId, userId));
        // 根据type 分组
        Map<String, List<Asset>> map = assets.stream().collect(Collectors.groupingBy(Asset::getType));
        List<AssetTypeSumResponse> assetTypeSumResponses = new ArrayList<>();
        for (Map.Entry<String, List<Asset>> entry : map.entrySet()) {
            String type = entry.getKey();
            List<Asset> assetList = entry.getValue();
            BigDecimal sum = assetList.stream().map(asset -> BigDecimal.valueOf(asset.getAmount()))
                    .reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
            assetTypeSumResponses.add(AssetTypeSumResponse.builder().assetType(type).sum(sum).build());
        }
        return assetTypeSumResponses;
    }
}

